package com.my.springboot.tuling.pattern.strategy;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class Context {
    private Strategy strategy;

   /* public Context(Strategy strategy) {
        this.strategy = strategy;
    }*/

    public Map<String, Strategy> strategyMap = new HashMap();
    /**
     *每次创建新的策略类对象都需要消耗一定的时间和内存。如果我们需要多次调用同一个策略类，就会造成资源的浪费。
     * 一种解决方案是使用策略类的缓存，将已经创建的策略类对象缓存起来，避免重复创建
     **/
    public Context(String className) {
        System.out.println("map长度=" + strategyMap.size());
        if (strategyMap.containsKey(className)) {
            this.strategy = strategyMap.get(className);
        } else {
            try {
                Class<?> clazz = Class.forName(className);
                this.strategy = (Strategy) clazz.newInstance();
                strategyMap.put(className, strategy );
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }

    }

    public int executeOperation(int num1,int num2){
        return strategy.doOperation(num1, num2);
    }

    public static void main(String[] args) {
        Context context = new Context(new OperationAdd().getClass().getName());
        System.out.println("1+2=" + context.executeOperation(1,2));
        Context context2 = new Context(new OperationSubtract().getClass().getName());
        System.out.println("1-2=" + context.executeOperation(1,2));
    }
}
